import { _decorator, Component, Label, Node, Sprite, Animation, Color, Vec2, tween, instantiate, Button, v3, Prefab, SpriteFrame, AudioSource, AudioClip } from 'cc';
import { DiamondConsume, EventOper } from '../entity/Buildings';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { Building } from '../entity/Buildings';
import { BuildingUpGrade } from './BuildingUpGrade';
import VillageApi from '../api/VillageApi';
import { UserInfo } from '../common/UserInfo';
import { Events } from '../entity/Events';
import { EventType } from '../settings/const';
import ResManager from '../common/ResManager';
import { BuildingBtnCheck } from './BuildingBtnCheck';
import { BuildingLocalApi } from './BuildingLocalApi';
import { Debug } from './Debug';
import { BuildingList } from './BuildingList';
import { EventManager } from '../event/EventManager';
import { VillageController } from './VillageController';
import { Utils } from '../common/Utils';
import { SpaceBtn } from './SpaceBtn';
import { BManager } from '../entity/BManager';
import { AudioManager, Mp3Enum } from '../common/AudioManager';
const { ccclass, property } = _decorator;




@ccclass('Space')
export class Space extends Component {
    @property(Sprite)
    public default: Sprite;
    @property(Sprite)
    public building: Sprite;
   

    @property(Node)
    public arrow: Node;
    @property(Label)
    public time: Label;
    @property(Label)
    public level:Label
    @property(AudioSource)
    public audioSource:AudioSource
    @property(Prefab)
    public spaceTip: Prefab

    /**建筑物的数据对象Building */
    public buildData: Building



    /**倒计时的秒数 */
    public countDownTime: number = 0



    start() {

        this.building.node.active = false

        this.arrow.active = false


    }
    /**
     * 设置坑位上的数据
     * @param b 
     */
    async setData(b: BManager) {
        this.buildData = Building.createBuildingByBManager(b)

        if (this.buildData.id == 0) {
            this.default.node.active = true
            this.building.node.active = false
            this.arrow.active = false
        } else {
            this.default.node.active = false
            this.building.node.active = true
            this.level.string = this.buildData.level + ''
            this.level.node.parent.active = true
            if (this.buildData.maxLevel > this.buildData.level) {
                this.arrow.active = true
            }
        }

        try {
            this.building.spriteFrame = await this.buildData.getImg()
            this.setBuildingState()
        } catch (error) {
            
        }
           
        
       


        

    }

    /**坑位被点击 */
    async onClick() {
        console.log(`space click,${this.buildData.name},uid=${this.buildData.uid},gid=${this.buildData.gid},level=${this.buildData.level}`)

        // 这是先选择的建筑物，再选择空地
        if (VillageController.instance.curBuilding) {
            let isCan = this.buildData.canBuildOnSpace(VillageController.instance.curBuilding)
            if (isCan) {
                this.buildBuilding(VillageController.instance.curBuilding.id)
            }


            return
        }

        let ui = await UIManager.instance.openUI(PrefabEnum.SpaceBtn)
        ui.getComponent(SpaceBtn).setData(this)



    }


    /**
     * 设置建筑物的状态
     * @param e 
     */
    async setBuildingState() {
        this.audioSource.stop()

        let e = this.buildData.getBuildingEvent()
        this.unschedule(this.countDown)
        this.countDownTime = 0;
        this.time.string = ''
        this.time.node.parent.active = false


        if (!e) {
            return
        }

        let eStartTime = e.eStartTime
        let eTime = e.eTime
        let offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        if (offTime <= 0) {
            return
        }


        let str = ''
        if (e.eType == EventType.advBuild) {
            str = '建造中 '
            try {
                this.building.spriteFrame = await this.buildData.getBuildingImg()
            } catch (error) {
                
            }
                
            

            this.playBuildingAudio()
          
        }

        if (e.eType == EventType.destroy) {
            str = '拆除中 '

            this.playBuildingAudio()
        }


        this.time.string = str + Utils.secondToStr(offTime) + ''
        this.time.node.parent.active = true
        this.countDownTime = offTime

        this.schedule(this.countDown, 1, offTime - 1)
    }

    countDown() {
        let e = this.buildData.getBuildingEvent()
        let str = ''
        if (e.eType == EventType.advBuild) {
            str = '建造中 '

        }

        if (e.eType == EventType.destroy) {
            str = '拆除中 '
        }

        this.countDownTime--
        this.time.string = str + Utils.secondToStr(this.countDownTime) + ''
        if (this.countDownTime == 0) {
            this.time.string = ''
            this.time.node.parent.active = false

            this.scheduleOnce(() => {
                UserInfo.instance.refreshVillageDetail()


                if (e.eType == EventType.advBuild) {
                    AudioManager.instance.playOneShot(Mp3Enum.construction_complete)
        
                }
        
                if (e.eType == EventType.destroy) {
                    AudioManager.instance.playOneShot(Mp3Enum.construction_downgrade)
                }
            }, 2)
            


            // 建造或升级完成，更新本地数据
            // if (this.buildData.isBuilding) {
            //     BuildingLocalApi.buildComplete(this.buildData)
            // }
            // 拆除完成更新本地数据
            // if (this.buildData.isRemoving) {
            //     BuildingLocalApi.removeComplete(this.buildData)
            // }
        }
    }

    canBuildOnSpace() {
        let building = VillageController.instance.curBuilding
        if (!building) {
            return false
        }
        let isCan = this.buildData.canBuildOnSpace(building)

        return isCan
    }


    /**开启选择空地的提示
     * 
     */
    openSpaceTip() {
        if (!this.canBuildOnSpace()) {
            return
        }

        let tip = instantiate(this.spaceTip)
        this.node.addChild(tip)
        tip.position = v3(0, 120, 0)
    }

    /**关闭选择空地的提示 */
    closeSpaceTip() {
        let tip = this.node.getChildByName('spaceTip')
        tip?.destroy()
    }

    /**
     * 建造，
     * @param id 建筑的id
     */
    async buildBuilding(id) {
        await UIManager.instance.showLoading()

        let res = await VillageApi.buildingOper({
            gid: id,
            uid: this.buildData.uid
        })

        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.closeLoading()

        VillageController.instance.closeSpaceTip()

        // res = await VillageApi.getVillageEvents(EventType.advBuild)
        // console.log(res)

        VillageController.instance.moveCameraToSpace(this.buildData.uid)
    }

    async onRemove() {

        await UIManager.instance.showLoading()
        let res = await VillageApi.destroyBuilding(this.buildData.uid)
        console.log(`拆除${this.buildData.uid}:`, res)
        UserInfo.instance.refreshVillageDetail()
        UIManager.instance.closeLoading()

        VillageController.instance.moveCameraToSpace(this.buildData.uid)
        UIManager.instance.closeUI(PrefabEnum.BuildingList)
    }

    /**
    * 取消按钮点击的回调方法
    */
    async onCancel() {
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper({
            ac: EventOper.CANCEL,
            eid: this.buildData.getBuildingEvent().eHandle
        })
        UIManager.instance.closeLoading()
        console.log(`取消，事件句柄${this.buildData.getBuildingEvent().eHandle}:`, res)

        //更新本地数据
        // BuildingLocalApi.cancel(this.buildData)

        UserInfo.instance.refreshVillageDetail()



    }

     /**
     * 加速按钮点击的回调方法
     */
     async onSpeed() {
        let param = {
             ac: EventOper.CANCEL,
             eid: this.buildData.getBuildingEvent().eHandle
        }
        if (this.buildData.isBuilding) {
             param.ac = EventOper.SPEED_BUILD
             AudioManager.instance.playOneShot(Mp3Enum.construction_complete)
        }
        if (this.buildData.isRemoving) {
             param.ac = EventOper.SPEED_REMOVE
             AudioManager.instance.playOneShot(Mp3Enum.construction_downgrade)
        }
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`速拆与速建ac =${param.ac} ,del =${param.eid} `, res)

        UserInfo.instance.refreshVillageDetail()

        return

        //更新本地数据
        // BuildingLocalApi.speed(this.buildData)


        // 建造或升级完成，更新本地数据
        if (this.buildData.isBuilding) {
             BuildingLocalApi.buildComplete(this.buildData)
             // 记得扣除砖石哦
             UserInfo.instance.diamond -= DiamondConsume.BUILD
             EventManager.instance.emit(EventManager.EventType.RefreshDiamond, UserInfo.instance.diamond)
        }
        // 拆除完成更新本地数据
        if (this.buildData.isRemoving) {
             BuildingLocalApi.removeComplete(this.buildData)
             // 记得扣除砖石哦
             UserInfo.instance.diamond -= DiamondConsume.REMOVE
             EventManager.instance.emit(EventManager.EventType.RefreshDiamond, UserInfo.instance.diamond)
        }

       
   }

   async playBuildingAudio(){
    let clip = await ResManager.instance.loadAssetByUrl<AudioClip>(Mp3Enum.construction_building)
    this.audioSource.clip = clip;
    this.audioSource.play();
   }
}


